package com.taoge.p4.common.exception;


import com.taoge.p4.common.entity.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@Slf4j
public class BaseExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseData<?> handleException(Exception e) {
        log.error("e:", e);
        return ResponseData.error(e.getMessage());
    }

    @ExceptionHandler(ParamException.class)
    @ResponseBody
    public ResponseData<?> handleException(ParamException e) {
//        log.error("e:", e);
        ResponseData<Object> responseData = ResponseData.error(e.getCode(), e.getMsg());
        return responseData;
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseData<?> handleException(BusinessException e) {
        log.error("e:", e);
        ResponseData<Object> responseData = ResponseData.error(e.getCode(), e.getMsg());
        return responseData;
    }
    @ExceptionHandler(TokenException.class)
    @ResponseBody
    public ResponseData<?> handleException(TokenException e) {
        log.error("e:", e);
        ResponseData<Object> responseData = ResponseData.error(e.getCode(), e.getMsg());
        return responseData;
    }

    @ExceptionHandler(PayException.class)
    @ResponseBody
    public ResponseData<?> handleException(PayException e) {
        // TODO 发送通知给相关人员

        log.error("e:", e);
        return ResponseData.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return new
                ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }
}
